<?php
namespace app\home\controller;
use app\common\controller\Ossaliyun;
// 引用验证码
use think\captcha\Captcha;
// 引用tp的基础控制器
use think\Controller;
// 引入Db
use think\Db;
use think\Request;
// 引入语言包
use think\Lang;
use think\cache\driver\Redis;

class Index extends Controller
{
	public function __construct(){
		// 手动继承父级
		parent::__construct();
		
		$this->UserModel = model('User.User');
		
		$this->RecordModel = model('User.Record');
		
		$this->PostModel = model('Post.Post');
		
		$this->CollectModel = model('Post.Collect');
		
		$this->CommentModel = model('Post.Comment');
		
		// 获取用户表所有数据
		$UserList = model('User.User')->column('id,salt');

		// 获取cookie的数据
		$LoginUser = cookie('LoginUser') ? cookie('LoginUser') : '';

		// 存放id的字符串
		$userid = 0;

		foreach($UserList as $key => $value)
		{
			$UserSalt = md5($key.$value);

			if($LoginUser == $UserSalt)
			{
				$userid = $key;
				break;
			}
		}

		// 根据id去查询用户表 对象 => 数组 > toArray()
		$User = model('User.User')->find($userid);
		// $User = Db::table('pre_user')->find($userid);
		$userid = isset($User['id']) ? $User['id'] : 0;
		
		// 消费记录表
		// $sing = $this->RecordModel->whereTime('createtime','today')->where(['userid' => $User['id'],'state' => 4])->find();
		$sing = $this->RecordModel->whereTime('createtime','today')->where(['userid' => $userid,'state' => 4])->find();

		if($sing)
		{
			$User['sing'] = 1;
		}
		
		$User = $User ? $User : [];

		// 把用户数据给继承home公共控制器的子控制器
		$this->LoginUser = $User;
		

		// 赋值视图
		$this->assign([
			'LoginUser' => $User
		]);
	}
    public function redis(){
        $redis = new Redis();
//        $redis->set('name','邓先生');
        $redis->set('info','我叫邓先生');
        dump($redis->get('info'));
    }
    public function index()
    {
		// 接收分类id => 帖子 => 根据分类id去查询相应帖子
		$cateid = $this->request->param('cateid');
		// 帖子状态
		$state = $this->request->param('state','');

		// 采纳
		$accept = $this->request->param('accept',0);

		// 关键字
		$keyword = $this->request->param('keyword','');
		
		// 条件数组
		$where = [];

		if(!empty($cateid))
		{
			
			$where['cateid'] = $cateid;
		}

		if(!empty($state))
		{
			$where['state'] = $state;
		}

		if($accept == 0)
		{
			// where `accept` is null
			$where['accept'] = ['exp',Db::raw('is null')];
		}elseif($accept == 1)
		{
			$where['accept'] = ['exp',Db::raw('is not null')];
		}

		if(!empty($keyword))
		{
			$where['title'] = ['like',"%$keyword%"];
		}
		
		// 查询本周热议
		$HotThisWeekList = model('Post.Comment')->with(['post'])->field("COUNT(*) as num,comment.id")->whereTime('comment.createtime', 'week')->order('num desc')->group('comment.postid')->limit(5)->select();
		
		// 查询回帖周榜单
		$WeekList = model('Post.Comment')->with(['user'])->field('COUNT(*) AS weeklist , comment.userid')->group('comment.userid')->whereTime('comment.createtime','w')->order('weeklist','desc')->limit(5)->select();
		
		// halt($WeekList);
		
		$CateList = model('Post.Cate')->order('weigh','desc')->limit(7)->select();
		
		// 查询签到积分
		$SignPoint = model('config')->where('key','SignPoint')->value('value');
		
		$PostList = model('Post.Post')->with(['user','cate'])->where($where)->order('post.createtime','desc')->paginate(8,false,['query' => Request::instance()->param()]);
		return $this->fetch('',[
			'CateList' => $CateList,
			'cateid' => $cateid,
			'PostList' => $PostList,
			'SignPoint' => $SignPoint,
			'state' => $state,
			'accept' => $accept,
			'HotThisWeekList' => $HotThisWeekList,
			'WeekList' => $WeekList
		]);
    }
	
	 // 帖子详情
	public function info()
	{
		/* 帖子id */
		$postid = $this->request->param('postid',0);

		$post = $this->PostModel->with(['user','cate'])->where('post.id',$postid)->find();
		
		if(!$post){
			$this->error('帖子不存在，请重新选择');
		}
		
		// 浏览量按id进行更新
		$userid = !empty($this->LoginUser['id']) ? $this->LoginUser['id'] : 0;
		
		
		// 查询数据库是否有该用户id
		$User = $this->UserModel->find($userid);
		
		// 字符串转数组
		$VisitArr = explode(',',$post['visit']);
		
		// 有再做判断
		if($User){
		
		    // 判断在浏览中是否存在该用户id
			// 不存在
			if(!in_array($User['id'],$VisitArr)){
				// 加进数组
				$VisitArr[] = $User['id'];
				
				// 在进行转换成字符串;
				$VisitStr = implode(',',$VisitArr);
				
				// 把字符串的左边逗号去掉
				$VisitStr = ltrim($VisitStr,',');
				
				// 根据帖子id存储进去
				$this->PostModel->where('id',$postid)->update(['visit' => $VisitStr]);
				
			}
			
		}
		// 访问次数
		$VisitCount = !empty($VisitArr) ? count($VisitArr) : 1;
		
		// 查询是否收藏
		$result = $this->CollectModel->where(['userid' => $userid , 'postid' => $postid])->find();
		
		// 判断是否收藏
		// 1为收藏   0为未收藏
		$collect = null;
		
		if($result){
			$collect = 1;
		}else{
			$collect = 0;
		}
		
		// 查询回帖周榜单
		$WeekList = model('Post.Comment')->with(['user'])->field('COUNT(*) AS weeklist , comment.userid')->group('comment.userid')->whereTime('comment.createtime','w')->order('weeklist','desc')->limit(5)->select();
		
		// 查询评论数据
		$CommentList = model('Post.Comment')->with('user')->where('postid',$postid)->order('comment.createtime')->select();

		$CommentList = CommentTree($CommentList,0,$User);
		
		return $this->fetch('',[
			'post' => $post,
			'WeekList' => $WeekList,
			'userid' => $userid,
			'collect' => $collect,
			'VisitCount' => $VisitCount,
			'CommentList' => $CommentList
		]);
	}
	
	// 登录
	public function login(){
		// 
		if(cookie('LoginUser')){
			$this->success('您已经登录',url('home/user/index'),null,0);
		}
		
		if($this->request->isPost()){
			$params = $this->request->param();
			
			if(!captcha_check($params['vercode'])){
				$this->error('验证码错误','',null,0);
			}
			
			// 通过邮箱去查询数据库是否存在该用户
			$User = $this->UserModel->where(['email' => $params['email']])->find();
			
			// 查询出来的结果为空 说明该用户不存在
			if(!$User){
				$this->error('该用户不存在');
			}
			
			$password = md5($params['pass'].$User['salt']);
			
			if($password != $User['password']){
				$this->error('密码错误');
			}
			
			// 设置cookie
			// $data = [
			//     'id' => $User['id'],
			//     'email' => $User['email'],
			//     'nickname' => $User['nickname'],
			//     'vip' => $User['vip'],
			//     'auth' => $User['auth'],
			// 	'sex_text' => $User['sex_text'],
			// 	'sex' => $User['sex'],
			// 	'point' => $User['point'],
			// 	'avatar' => $User['avatar'] ? $User['avatar'] : '/static/home/images/avatar/default.png',
			// 	'cover' => $User['cover'] ? $User['cover'] : '/static/home/images/avatar/1.jpg',
			// ];
			
			$data = md5($User['id'].$User['salt']);
			
			// 存进cookie
			cookie('LoginUser',$data);
			
			// 跳转
			$this->success('登录成功',url('home/user/index',['userid'=>$User['id']]),null,0);
			
		}
		
		return $this->fetch();
	
	}

    public function lang()
    {
        // 动态使用模板布局
        $this->view->engine->layout(false);
        return $this->fetch();
    }

    // 切换语言
    public function replaceLang()
    {
        $lang = Lang::detect();
        switch ($lang) {
            case 'zh-cn':
                cookie('think_var', 'en-us');
                $this->success('切换英文成功!',url('/home/index/lang'));
                break;
            case 'en-us':
                cookie('think_var', 'zh-cn');
                $this->success('切换中文成功!',url('/home/index/lang'));
                break;
            //其它语言
            default:
                cookie('think_var', 'zh-cn');
                break;
        }
    }

    public function ossaliyun()
    {
        if(isset($_FILES) && isset($_FILES['favicon'])){
            $file = request()->file('favicon');
            if(!$file->isValid()){
                return '不合法文件';
            }
            // 获取文件扩展名
            $ext = substr($file->getInfo('name'), strrpos($file->getInfo('name'), '.'));
            // 新的文件名
            $newfile = md5(time().rand(1000,9999)) . $ext;
            @error_reporting (E_ALL & ~E_NOTICE & ~E_WARNING);
            // 将文件上传到指定的Oss仓库
            $Oss = new Ossaliyun();
            $res = $Oss->uploadOssFile($newfile,$file->getRealPath());
            dump($res);
        }

        return $this->fetch();
    }
	
	 // 签到
	public function sign()
	{
		if($this->request->isAjax())
		{
			if(empty($this->LoginUser))
			{
				$this->error('请先登录');
			}

			// 查询今天是否签到
			$sing = $this->RecordModel->whereTime('createtime','today')->where(['userid' => $this->LoginUser['id'],'state' => 4])->find();

			if($sing)
			{
				$this->error('您已签到了');
			}

			/* 
				消费记录表 新增一条记录
				用户表 更新积分
			*/

			// 开启事务
			$this->UserModel->startTrans();
			$this->RecordModel->startTrans();

			// 获取到签到的积分
			$SignPoint = model('config')->where(['key' => 'SignPoint'])->value('value');

			// 用户的积分加上签到的积分
			$Point = bcadd($this->LoginUser['point'],$SignPoint);

			// 更新数据
			$UserData = [
				'id' => $this->LoginUser['id'],
				'point' => $Point
			];

			$UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

			if($UserStatus === FALSE)
			{
				$this->error('签到失败');
			}

			// 消费记录
			$RecordData = [
				'userid' => $this->LoginUser['id'],
				'point' => $SignPoint,
				'content' => "您在".date('Y-m-d H:i',time())."通过【签到】获取了{$SignPoint}积分",
				'state' => 4
			];

			$RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);

			if($RecordStatus === FALSE)
			{
				$this->UserModel->rollback();
				$this->error($this->RecordModel->getError());
			}

			if($UserStatus === FALSE || $RecordStatus === FALSE)
			{
				$this->UserModel->rollback();
				$this->RecordModel->rollback();
				$this->error('签到失败');
			}else{
				$this->UserModel->commit();
				$this->RecordModel->commit();
				$this->success('签到成功');
			}

		}
	}

	// 注册页面
	public function register(){
		//
		if(cookie('LoginUser')){
			$this->success('您已经登录',url('home/user/index'),null,0);
		}
		// 获取表单请求过来的数据
		if($this->request->isPost()){
			//get post
			$params = $this->request->param();
			// halt($params);
			// 验证码验证
			if(!captcha_check($params['vercode'])){
				// 跳转中间页
				$this->error('验证码错误');
			}
			// 判断二次密码是否一致
			if($params['pass'] != $params['repass']){
				$this->error('密码与确认密码不一致');
			}
			// 生成密码盐
			$salt = build_ranstr();
			
			// 进行加密
			$password = md5($params['pass'].$salt);
			
			 // Db类或者模型增删改查 用Db类查询注册的赠送积分
			 $point = Db::name('config')->where('key','RegisterPoint')->value('value');
			 
			 // 封装插入数据库的数组
			 $data = [
			    'email' => $params['email'],
			    'nickname' => $params['nickname'],
			    'password' => $password,
			    'salt' => $salt,
			    'sex' => 0,
			    'auth' => 0,
			    'vip' => 1,
			    'point' => $point
			];
			
			// 验证
			$result = $this->UserModel->validate('common/User/User')->save($data);
			
			if($result === FALSE){
				$this->error($this->UserModel->getError());
			}else{
				$this->success('注册成功',url('home/index/login'),null,0);
			}
		}
		// 输出视图
		return $this->fetch();
	}
	
	// 验证邮箱
	public function auth()
	{
		$email = $this->request->param('email');

		$UserList = $this->UserModel->column('email,salt');

		// 定义字符串
		$UserEmail = '';

		foreach($UserList as $key => $value)
		{
			$userSalt = md5($key.$value);

			if($email == $userSalt)
			{
				$UserEmail = $key;
				break;
			}
		}

		$User = $this->UserModel->where('email',$UserEmail)->find();

		if(!$User)
		{
			$this->error('无效邮箱');
		}

		$data = [
			'id' => $User['id'],
			'auth' => 1
		];

		// isUpdate(true) => 更新操作
		$result = $this->UserModel->isUpdate(true)->save($data);

		if($result === FALSE)
		{
			$this->error('认证失败');
		}else{
			cookie('LoginUser',md5($User['id'].$User['salt']));
			$this->success('认证成功',url('home/user/index'),null,0);
		}
	}

	
	// 验证码
	public function vercode(){
		$config = [
			'length'=>4,
			// 验证码字体大小
			'fontSize'=>20,    
			'imageW'=>150,
			'imageH'=>40
		];
		$captcha = new Captcha($config);
		return $captcha->entry();
	}
	
	// 退出登录
	public function loginout(){
		cookie('LoginUser',null);
		$this->success('退出成功',url('home/index/login'),null,0);
	}
}
